package com.lxj.user.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lxj.user.mapper.UserMapper;
import com.lxj.user.service.UserService;
import com.lxj.utils.common.CommonResult;
import com.lxj.utils.entity.Permission;
import com.lxj.utils.entity.User;
import com.lxj.utils.vo.UserRoleRelation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.HashMap;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public CommonResult findAll(User user) {
        PageHelper.startPage(user.getPageNum(), user.getPageSize());
        PageInfo<User> pageInfo = new PageInfo<>(this.userMapper.findAll(user));
        HashMap<String, Object> map = new HashMap<>();
        map.put("list", pageInfo.getList());
        map.put("number", pageInfo.getTotal());
        return CommonResult.success(map);
    }

    @Override
    public CommonResult add(User user) {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(user.getPassword());
        user.setPassword(encode);
        int count = userMapper.add(user);
        if (count == 1) {
            return CommonResult.success(count);
        }
        return CommonResult.failed("添加失败！");
    }

    @Override
    public CommonResult delete(Integer[] id) {
        int result = userMapper.delete(id);
        if (result == 0) {
            return CommonResult.failed();
        }
        return CommonResult.success(result);
    }

    @Override
    public CommonResult findRole(Integer id) {
        List<UserRoleRelation> list = userMapper.findRole(id);
        return CommonResult.success(list);
    }

    @Override
    public CommonResult addRole(UserRoleRelation urr) {
        updateUserType(urr);
        int count = userMapper.addRole(urr);
        Assert.notNull(count,"添加失败");
        return CommonResult.success(count);
    }

    @Override
    public CommonResult deleteRole(UserRoleRelation urr) {
        int count = userMapper.deleteRole(urr);
        Assert.notNull(count,"删除失败");
        return CommonResult.success(count);
    }

    @Override
    public CommonResult findName(String username) {
        String name = userMapper.findName(username);
        return CommonResult.success(name);
    }

    @Override
    public List<Permission> getPermissionsByUserId(Integer id) {
        return userMapper.getPermissionsByUserId(id);
    }

    public void updateUserType(UserRoleRelation urr){
        userMapper.updateUserType(urr);
    }
}
